import Request from 'utils/request';

const dataURLtoFile = (dataurl, filename) => {
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime
  });
};

export default class UploadFileApi {
  static getQiniuToken() {
    const apiName = 'api/qiniu/getQiniuToken';

    return Request.post(apiName).then(res => {
      return res.data;
    }).catch(error => {
      return error;
    });
  }

  static async uploadImg(file, callback) {
    let token = await this.getQiniuToken();
    if (_.isError(token)) {
      return '';
    }

    return Request.postImgToQiniu(file, token, callback).then(imgUrl => {
      return imgUrl;
    });
  }

  static async uploadBase64ImgList(uploadImgList){
    let token = await this.getQiniuToken();
    if (_.isError(token)) {
      return '';
    }

    let filePromiseList = [];
    for (let i = 0; i < uploadImgList.length; i++) {
      const uploadImg = uploadImgList[i];
      let name = `image_${_.random(0, 1000, false)}`;
      let file = dataURLtoFile(uploadImg.base64,name);
      filePromiseList.push(Request.postImgToQiniu(file, token));
    }
    return Promise.all(filePromiseList).then(urlList=>{
      for (let i = 0; i < uploadImgList.length; i++) {
        let uploadImg = uploadImgList[i];
        uploadImg.url = urlList[i];
      }
      return uploadImgList;
    });
  }
}
